package de.tum.wi.som.rcpsp.business.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.tum.wi.som.rcpsp.business.PriorizationStrategy;
import de.tum.wi.som.rcpsp.entities.Activity;

/**
 * Special {@link PriorizationStrategy}. It sorts the list of activities by its
 * remaining work content. The more work content an activity has remaining, the
 * more important it is.
 * 
 */
public class MostWorkContentRemainingStrategy implements PriorizationStrategy {

	@Override
	public List<Activity> execute(List<Activity> activities) {
		// TODO Auto-generated method stub

		Collections.sort(activities, new Comparator<Activity>() {

			@Override
			public int compare(Activity activity1, Activity activity2) {
				int mwrActivity1 = calculateMWR(activity1);
				int mwrActivity2 = calculateMWR(activity2);
				if (mwrActivity1 > mwrActivity2) {
					return -1;
				}
				if (mwrActivity1 < mwrActivity2) {
					return +1;
				} else
					return 0;
			}

		});
		return activities;
	}

	private int calculateMWR(Activity activity) {
		int mostWorkContentRemaining;
		mostWorkContentRemaining = activity.getNeededResources();
		Set<Activity> followerActivities = getFollowersWithoutDuplicates(activity);
		for (Activity activity2 : followerActivities) {
			mostWorkContentRemaining += activity2.getNeededResources();
		}
		return mostWorkContentRemaining;
	}

	private Set<Activity> getFollowersWithoutDuplicates(Activity activity) {
		Set<Activity> noDuplicateFollowers = new HashSet<Activity>();
		Set<Activity> followerActivities = activity.getFollowerActivities();
		for (Activity activity2 : followerActivities) {
			noDuplicateFollowers.add(activity2);
			noDuplicateFollowers
					.addAll(getFollowersWithoutDuplicates(activity2));
		}
		return noDuplicateFollowers;
	}

	@Override
	public String toString() {
		return "MWR";
	}
}
